package com.kwin.reqexcel.util;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * @author : wangkai
 * @version V1.0
 * @Package com.kwin.excel.util
 * @Description:
 * @date 2021年10月19日 10:42
 **/
public enum LocalDateStringConverter implements Converter<LocalDate> {
    INSTANCE;
    
    @Override
    public Class supportJavaTypeKey() {
        return LocalDate.class;
    }
    
    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }
    
    @Override public LocalDate convertToJavaData(CellData cellData, ExcelContentProperty excelContentProperty,
        GlobalConfiguration globalConfiguration) throws Exception {
        if (excelContentProperty == null || excelContentProperty.getDateTimeFormatProperty() == null) {
            return LocalDate.parse(cellData.getStringValue());
        }
        else {
            DateTimeFormatter formatter = DateTimeFormatter
                .ofPattern(excelContentProperty.getDateTimeFormatProperty().getFormat());
            return LocalDate.parse(cellData.getStringValue(), formatter);
        }
    }
    
    @Override public CellData convertToExcelData(LocalDate localDate, ExcelContentProperty excelContentProperty,
        GlobalConfiguration globalConfiguration) throws Exception {
        DateTimeFormatter formatter;
        if (excelContentProperty == null || excelContentProperty.getDateTimeFormatProperty() == null) {
            formatter = DateTimeFormatter.ISO_LOCAL_DATE;
        }
        else {
            formatter = DateTimeFormatter.ofPattern(excelContentProperty.getDateTimeFormatProperty().getFormat());
        }
        return new CellData<>(localDate.format(formatter));
    }
}
